package com.jdew.thkj.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;

import java.io.File;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

/**
 * Created by yangyang on 2017/9/19.
 */

public class DeviceUtils {

        private DeviceUtils() {
            throw new UnsupportedOperationException("u can't instantiate me...");
        }

        /**
         * 判断设备是否root
         *
         * @return the boolean{@code true}: 是<br>{@code false}: 否
         */
        public static boolean isDeviceRoot() {
            String su = "su";
            String[] locations = {"/system/bin/", "/system/xbin/", "/sbin/", "/system/sd/xbin/", "/system/bin/failsafe/",
                    "/data/local/xbin/", "/data/local/bin/", "/data/local/"};
            for (String location : locations) {
                if (new File(location + su).exists()) {
                    return true;
                }
            }
            return false;
        }

        /**
         * 获取设备系统版本号
         *
         * @return 设备系统版本号
         */
        public static int getSDKVersion() {
            return Build.VERSION.SDK_INT;
        }


        /**
         * 获取设备AndroidID
         *
         * @param context 上下文
         * @return AndroidID
         */
        @SuppressLint("HardwareIds")
        public static String getAndroidID(Context context) {
            return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        }


        /**
         * 获取设备MAC地址
         * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>}</p>
         *
         * @param context 上下文
         * @return MAC地址
         */
        @SuppressLint("HardwareIds")
        private static String getMacAddressByWifiInfo(Context context) {
            try {
                WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                if (wifi != null) {
                    WifiInfo info = wifi.getConnectionInfo();
                    if (info != null) return info.getMacAddress();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "02:00:00:00:00:00";
        }

        /**
         * 获取设备MAC地址
         * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
         *
         * @return MAC地址
         */
        private static String getMacAddressByNetworkInterface() {
            try {
                List<NetworkInterface> nis = Collections.list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface ni : nis) {
                    if (!ni.getName().equalsIgnoreCase("wlan0")) continue;
                    byte[] macBytes = ni.getHardwareAddress();
                    if (macBytes != null && macBytes.length > 0) {
                        StringBuilder res1 = new StringBuilder();
                        for (byte b : macBytes) {
                            res1.append(String.format("%02x:", b));
                        }
                        return res1.deleteCharAt(res1.length() - 1).toString();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "02:00:00:00:00:00";
        }


        /**
         * 获取设备厂商
         * <p>如Xiaomi</p>
         *
         * @return 设备厂商
         */

        public static String getManufacturer() {
            return Build.MANUFACTURER;
        }

        /**
         * 获取设备型号
         * <p>如MI2SC</p>
         *
         * @return 设备型号
         */
        public static String getModel() {
            String model = Build.MODEL;
            if (model != null) {
                model = model.trim().replaceAll("\\s*", "");
            } else {
                model = "";
            }
            return model;
        }

        /**
         * 关机
         * <p>需系统权限 {@code <android:sharedUserId="android.uid.system"/>}</p>
         *
         * @param context 上下文
         */
        public static void shutdown(Context context) {
            Intent intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
            intent.putExtra("android.intent.extra.KEY_CONFIRM", false);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }


        /**
         * 重启
         * <p>需系统权限 {@code <android:sharedUserId="android.uid.system"/>}</p>
         *
         * @param context 上下文
         */
        public static void reboot(Context context) {
            Intent intent = new Intent(Intent.ACTION_REBOOT);
            intent.putExtra("nowait", 1);
            intent.putExtra("interval", 1);
            intent.putExtra("window", 0);
            context.sendBroadcast(intent);
        }

        /**
         * 重启
         * <p>需系统权限 {@code <android:sharedUserId="android.uid.system"/>}</p>
         *
         * @param context 上下文
         * @param reason  传递给内核来请求特殊的引导模式，如"recovery"
         */
        public static void reboot(Context context, String reason) {
            PowerManager mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            try {
                mPowerManager.reboot(reason);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    public static boolean checkPackage(Context context ,String packageName)
    {
        if (packageName == null || "".equals(packageName))
            return false;
        try{
            context.getPackageManager().getApplicationInfo(packageName, context.getPackageManager().GET_UNINSTALLED_PACKAGES);
            return true;
        }catch (PackageManager.NameNotFoundException e){
            return false;
        }

    }

    /**
     * 判断网络情况
     * @param context 上下文
     * @return false 表示没有网络 true 表示有网络
     */
    public static boolean isNetworkAvalible(Context context) {
        // 获得网络状态管理器
        if(null!=context){
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            if (connectivityManager == null) {
                return false;
            } else {
                // 建立网络数组
                NetworkInfo[] net_info = connectivityManager.getAllNetworkInfo();

                if (net_info != null) {
                    for (int i = 0; i < net_info.length; i++) {
                        // 判断获得的网络状态是否是处于连接状态
                        if (net_info[i].getState() == NetworkInfo.State.CONNECTED) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }
}
